package util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * Get MD5 code from a string and make the result into a string too.
 * 
 * @author Cylixstar
 * 
 */
public class MD5 {
	/**
	 * Just invoke this method to get the MD5 in string of the given string.
	 * 
	 * @return the MD5 code in string
	 * 
	 */
	public static String getMD5(String str) {
		StringBuilder result = new StringBuilder();
		final char codemap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F' };
		byte bstr[] = str.getBytes();
		int step;
		try {
			MessageDigest md5 = MessageDigest.getInstance("md5");
			bstr = md5.digest(bstr);
			for (step = 0; step < bstr.length; step++) {
				result.append(codemap[bstr[step] & 15]);
				result.append(codemap[bstr[step] >>> 4 & 15]);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result.toString();
	}
}
